package com.sdx.console.product.web;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.sdx.common.entity.ResCloudFile;
import com.sdx.common.service.ResCloudFileService;
import com.sdx.common.utils.FileUtils;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.common.utils.Utils;
import com.sdx.console.content.entity.EbookMain;
import com.sdx.console.content.service.EbookMainService;
import com.sdx.console.product.entity.SaleProduct;
import com.sdx.console.product.service.SaleProductService;
import com.sdx.service.ConfigService;
import com.sdx.third.AliOSSApi;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.mockito.internal.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;


/**
 * SaleProduct 接口
 */
@RequestMapping("/product/saleProduct")
@Controller
public class SaleProductController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(SaleProductController.class);
    private static final String MODEL = "/product/saleProduct";

	@Resource
	ResCloudFileService resCloudFileService;

    @Resource
	private SaleProductService saleProductService;

    @Resource
	private EbookMainService ebookMainService;

	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {
		EbookMain ebookMain = new EbookMain();
		ebookMain.setBookStatus(1);
		List<EbookMain> list = ebookMainService.getSqlManager().template(ebookMain);
		view.addObject("ebookList",list);
		view.addObject("ebookJson", JSON.toJSONString(list));
	}

    /* 页面 */

    @GetMapping("/index.do")
    @Function("product.saleProduct.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("product.saleProduct.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,Integer productId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        SaleProduct saleProduct = saleProductService.queryById(productId);
        view.addObject("saleProduct", saleProduct);
		setPageParam(view,request);
		try {
			view.addObject("saleProductJson", JacksonUtils.toJsonString(saleProduct,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("product.saleProduct.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		setPageParam(view,request);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("product.saleProduct.query")
    @ResponseBody
    public JsonResult<PageQuery> list(SaleProduct condtion)
    {
        PageQuery page = condtion.getPageQuery();
        saleProductService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,SaleProduct saleProduct,HttpServletRequest request
							,MultipartFile coverFile
	) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/product/"+dir+"/";
		String bucketName = "sdxcomm";
		if (!FileUtils.isEmptyFile(coverFile)) {
			try
			{
		        String coverFileNamePair = FileUtils.upload(subPath,coverFile);
		        String coverStoreFile = coverFileNamePair.split("::")[0];
		        coverStoreFile = subPath+coverStoreFile;
				AliOSSApi.uploadLocalFile(FileUtils.getRoot()+coverStoreFile,bucketName,coverStoreFile.substring(1));
				String coverUrl = "https://sdxcomm."+ ConfigService.ossDomain+coverStoreFile;
				saleProduct.setCover(coverUrl);
				resCloudFileService.insertResFile(ResCloudFile.ALI,coverStoreFile,coverUrl,"a","老师工作照");
			}catch(Exception e) {
				e.printStackTrace();
				result.setCode(JsonReturnCode.IO_ERROR.getCode());
				result.setMsg(e.getMessage());
			}
		}
		CoreUser user = getLoginUser(request);
    	if (isNew) {
			saleProduct.setCreatedBy(user.getId().intValue());
			saleProduct.setCreatedName(user.getName());
			saleProduct.setCreatedTime(new Date());
			saleProductService.save(saleProduct);
		} else {
    		if(StringUtils.isEmpty(saleProduct.getBookIds())||saleProduct.getProductType()!=996){
				saleProduct.setBookIds(" ");
			}
			saleProduct.setUpdatedBy(user.getId().intValue());
			saleProduct.setUpdatedName(user.getName());
			saleProduct.setUpdatedTime(new Date());
			saleProductService.updateTemplate(saleProduct);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("product.saleProduct.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)SaleProduct saleProduct,HttpServletRequest request
							,@RequestParam("coverFile") MultipartFile coverFile
		)
    {

        return save(true,saleProduct,request
					,coverFile
		);
    }

    @PostMapping("/update.json")
    @Function("product.saleProduct.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  SaleProduct saleProduct,HttpServletRequest request
							,@RequestParam("coverFile") MultipartFile coverFile
		) {
		return save(false,saleProduct,request
		,coverFile
		);
    }


   
    @GetMapping("/view.json")
    @Function("product.saleProduct.query")
    @ResponseBody
    public JsonResult<SaleProduct>queryInfo(Integer productId) {
        SaleProduct saleProduct = saleProductService.queryById( productId);
        return  JsonResult.success(saleProduct);
    }

    @PostMapping("/delete.json")
    @Function("product.saleProduct.del")
    @ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        saleProductService.batchDelSaleProduct(idList);
        return JsonResult.success();
    }
    

}
